package com.hua.store.web.filter;

import com.hua.store.domin.User;
import com.hua.store.service.UserService;
import com.hua.store.service.impl.UserServiceImpl;
import com.hua.store.utils.CookUtils;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.sql.SQLException;

public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        try {
            User user = (User) req.getSession().getAttribute("loginUser");
            if (user != null) {
                filterChain.doFilter(req, servletResponse);
            } else {
                Cookie[] cookies = req.getCookies();
                Cookie cookie = CookUtils.getCookieByName("auto_login", cookies);
                if (cookie == null) {
                    filterChain.doFilter(req, servletResponse);
                } else {
                    String value = cookie.getValue();
                    String username = value.split("#hua#")[0];
                    String password = value.split("#hua#")[1];

                    User user1 = new User();
                    user1.setUsername(username);
                    user1.setPassword(password);
                    UserService service = new UserServiceImpl();
                    user = service.userLogin(user1);
                    req.getSession().setAttribute("loginUser", user);
                    filterChain.doFilter(req, servletResponse);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            filterChain.doFilter(req, servletResponse);
        }
    }
}
